<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//当函数不存在的时候才去创建
if (!function_exists('randstr')) {
    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    function randstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

/**
 * $to 收件人的地址
 * $msg 收件内容
 */
function send($to, $msg = '')
{
    // var_dump(APP_PATH.'phpmail/class.phpmailer.php');
    // var_dump(is_file(APP_PATH.'phpmail/class.phpmailer.php'));
    // exit;
    //引入邮件发送的类
    // APP_PATH TP常量 application
    include_once(APP_PATH . 'phpmail/class.phpmailer.php');

    //实例化这个邮箱类
    $mail = new PHPMailer(true);

    //设置发送的协议 smtp
    $mail->IsSMTP();

    //是否验证
    $mail->SMTPAuth = true;

    //设置端口  发信服务器端口号,加密端口一般是465，普通端口25
    $mail->Port = 25;   //465 宝塔放行 465  服务器 网络安全组 入\出

    //设置第三方服务
    $mail->Host = "smtp.qq.com";   // ssl://smtp.163.com 开启openssl服务 宝塔默认开启

    //设置第三方的账号密码 密码不是登录密码，是授权密码
    $mail->Username   = "1413806163@qq.com";
    $mail->Password   = "rqelrrajitkncajb";

    //回复人
    $mail->AddReplyTo("1413806163@qq.com", "Fly官方社区");

    $mail->From       = "1413806163@qq.com";  //发件人地址
    $mail->FromName   = "Fly官方社区";    //发件人名称

    //添加收件人
    $mail->AddAddress($to);

    $mail->Subject  = "Fly论坛邮箱认证"; //邮件主题

    //设置多少个字符换行 80字符
    $mail->WordWrap   = 80;

    // ssl协议
    // $mail->SMTPSecure = 'ssl';

    $mail->MsgHTML($msg);    //发送内容

    //发送的内容里面是否允许发送带html的
    $mail->IsHTML(true);

    //成功发送返回true 失败返回false
    return $mail->Send();
}

/**
 * 图片上传
 */
function upload($name = 'img')
{
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file($name);
    if ($file) {
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            //返回路径+文件名
            return str_replace("\\", "/", $info->getSaveName());
        }
        return false;
    }
    return false;
}

/*
创建一个公共函数，来处理评论的递归  处理数据
$list：评论数据
$pid： 父级，0：表示第一层
$User： 用户信息
*/
function CommentTree($list, $pid = 0, $User)
{
    $data = [];

    if ($list) {

        // 循环$list
        foreach ($list as $item) {
            // 处理评论的点赞
            if (!empty($item['like'])) {

                // 计算评论点赞数量
                $LikeArr = explode(',', $item['like']);
                $LikeArr = array_filter($LikeArr);
                $LikeCount = is_array($LikeArr) ? count($LikeArr) : 0;
                $item['like_count'] = $LikeCount;

                //判断当前这一条评论是不是本人点过赞
                if (in_array($User['id'], $LikeArr)) {
                    $item['active'] = true;
                } else {
                    $item['active'] = false;
                }
            } else {
                //当like字段为空
                $item['like_count'] = 0;
            }

            //id = 1 pid = 0, 如果有上级ID
            if ($item['pid']  == $pid) {
                //找出相等pid值，给当前的评论新增一个自定义属性
                //递归找子集
                $item['child'] = CommentTree($list, $item['id'], $User);
                $data[] = $item;
            }
        }
    }

    return $data;
}

/*
处理递归循环输出  处理输出
$list：评论循环数据
$post：帖子详细信息
$flag: 楼主，第一层，第一次回复
$output: 评论HTML字符
*/
function CommentHtml($list, $post, $flag = "top", $output = "")
{

    foreach ($list as $key => $item) {

        //外边距
        $PaddingLeft = $item['level'] * 3;

        $output .= "<li style='padding-left:{$PaddingLeft}em' class='jieda-daan'>";

        //头像
        $output .= "<div class='detail-about detail-about-reply'>";
        // 头像
        $url = url('home/user/index', ['userid' => $item['userid']]);
        $output .= "<a class='fly-avatar' href='$url'>";

        //判断头像
        if (is_file($item['user']['avatar'])) {
            $avatar = $item['user']['avatar'];
            $output .= "<img src='/$avatar' />";
        } else {
            $output .= "<img src='/assets/home/images/avatar.jpg' />";
        }
        $output .= "</a>";


        // 用户信息
        $output .= "<div class='fly-detail-user'>";
        $output .= "<a href='javascript:void(0)' class='fly-link'>";
        $nickname = $item['user']['nickname'];
        $output .= " <cite>$nickname</cite>";

        if ($item['user']['auth'] > 0) {
            $output .= "<i class='iconfont icon-renzheng'></i>";
        }
        $output .= "</a>";

        //楼主
        if ($key == 0 && $flag == 'top') {
            $output .= "<span style='color:#FF7200'>(楼主)</span>";
        }

        //判断是否为发帖人
        if ($item['userid'] == $post['userid']) {
            $output .= "<span style='color:#5FB878' >(发帖人)</span>";
        }
        $output .= "</div>";

        // 评论时间
        $output .= "<div class='detail-hits'>";
        $output .= "<span>{$item['createtime']}</span>";
        $output .= "</div>";


        // 采纳图标
        if ($item['accept'] == 1) {
            $output .= "<i class='iconfont icon-caina' title='最佳答案'></i>";
        }
        $output .= "</div>";

        // 评论内容
        $output .= "<div class='detail-body jieda-body photos'>";
        $output .= "<p>{$item['content']}</p>";
        $output .= "</div>";

        // 回复
        if (cookie('LoginUser')) {
            $output .= "<div class='jieda-reply'>";

            // var_dump($item['id']);
            // exit;
            // 点赞
            if (isset($item['active'])) {
                $output .= "<span class='jieda-zan zanok' type='zan'>";
            } else {
                $output .= "<span class='jieda-zan' type='zan'>";
            }
            $id = $item['id'];
            $output .= "<i class='iconfont icon-zan thumbs' data-id='$id'></i>";
            $output .= "<em>{$item['like_count']}</em>";
            $output .= "</span>";

            // 回复
            if (!$post['accept']) {
                $pid = $item['id'];
                $nickname2 = $item['user']['nickname'];
                $output .= "<a href='#comment' class='reply' type='reply' data-pid='$pid' data-nickname='$nickname2'>";
                $output .= "<i class='iconfont icon-svgmoban53'></i>\r\n回复";
                $output .= "</a>";
            }
            $output .= "<div class='jieda-admin'>";
            // (登录的人 == 发帖userid)发帖人  || 评论本人（评论人 == 登录的人）

            // (登录的人 == 发帖userid)发帖人  || 评论本人（评论人 == 登录的人）

            $userid = cookie('LoginUser')['id'];
            if ($userid == $post['userid'] || $userid == $item['userid']) {
                if (!$post['accept']) {
                    $id = $item['id'];
                    $output .= " <span class='delect' data-commid='{$item['id']}' type='del'>删除</span>";
                }
            }


            if ($userid == $post['userid']) {
                if (!$post['accept']) {
                    $output .= "<span class='accept' data-comid='{$item['id']}' class='jieda-accept' type='accept'>";
                    $output .= "采纳";
                    $output .= "</span>";
                }
            }
            $output .= "</div>";


            $output .= "</div>";
        }
        $output .= "</li>";

        //判断是否有子集
        if (!empty($item['child'])) {
            $output = CommentHtml($item['child'], $post, 'son', $output);
        }
    }

    return $output;
}

if (!function_exists('build_code')) {

    /**
     * 生成唯一订单号
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix.$order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}